package com.example.campus.service.impl;

import com.example.campus.exception.QueryFailedException;
import com.example.campus.mapper.CategoryMapper;
import com.example.campus.mapper.InfoCateLinkMapper;
import com.example.campus.pojo.dto.CategoryAddDTO;
import com.example.campus.pojo.dto.CategoryPageQueryDTO;
import com.example.campus.pojo.entity.Category;
import com.example.campus.result.PageResult;
import com.example.campus.service.CategoryService;
import com.example.campus.utils.constant.MessageConstant;
import com.example.campus.utils.constant.RedisConstant;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private InfoCateLinkMapper infoCateLinkMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public PageResult getCategoryList(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());
        Page<Category> page = categoryMapper.getCategoryList(categoryPageQueryDTO);
        long total = page.getTotal();
        if (total < 1) {
            throw new QueryFailedException(MessageConstant.QUERY_NULL);
        }
        List<Category> records = page.getResult();
        return new PageResult(total, records);
    }

    @Override
    public void addCategory(CategoryAddDTO categoryAddDTO) {
        categoryMapper.addCategory(categoryAddDTO);
    }

    @Override
    public void updateCategory(Category category) {
        categoryMapper.updateCategory(category);

        List<Long> infoIds = infoCateLinkMapper.getByCategoryId(category.getId());
        for (Long infoId : infoIds) {
            String key = RedisConstant.CACHE_INFO_KEY + infoId;
            stringRedisTemplate.delete(key);
        }
    }

    @Override
    public void deleteCategory(Long id) {
        infoCateLinkMapper.deleteByCategoryId(id);
        categoryMapper.deleteCategoryById(id);
    }

    @Override
    public Page<Category> getCategories() {
        return categoryMapper.getCategoryList(null);
    }
}
